package cn.wj.school.common.manager;

import cn.wj.school.common.dto.BaseMsg;
import cn.wj.school.common.dto.PingReq;
import cn.wj.school.common.enums.MsgType;

import io.netty.channel.Channel;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @Author: yueding
 * @Description:
 * @Date: Created in 17:14 2018/12/29
 * @Modified By: yueding Copyright(c) cai-inc.com
 */
public class ManagerBuilder {

    private static ManagerBuilder managerBuilder;

    private final Map<String, BaseManager> builders;

    private ManagerBuilder() {
        this.builders = new HashMap<>();
        ServiceLoader<BaseManager> serviceLoader = ServiceLoader.load(BaseManager.class);
        for (BaseManager manager : serviceLoader) {
            builders.put(manager.beanName(), manager);
        }
    }

    public static ManagerBuilder getManagerBuilder() {
        if (managerBuilder == null) {
            managerBuilder = new ManagerBuilder();
        }
        return managerBuilder;
    }

    /**
     * 执行
     * @param msg
     */
    public void exec(BaseMsg msg, Channel channel) {
        String beanName = msg.getMsgType().getBeanName();
        if (builders.containsKey(beanName)) {
            builders.get(beanName).handleMsg(msg, channel);
        }
    }

    public BaseMsg getBaseMsg (int msgType) {
        Map <Integer, String> map = MsgType.getBeanMap();
        if (map.containsKey(msgType)) {
            String beanName = map.get(msgType);
            if (builders.containsKey(beanName)) {
                return builders.get(beanName).getObject();
            }
        }
        return new PingReq();
    }
}
